package cn.itsource.ymcc.config;


import cn.itsource.ymcc.constant.Constants;
import cn.itsource.ymcc.domain.Login;
import cn.itsource.ymcc.domain.Permission;
import cn.itsource.ymcc.mapper.LoginMapper;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * security 的用户认证
 */
@Component
public class UserDetailServiceImpl implements UserDetailsService {
    @Autowired
    private LoginMapper loginMapper;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    /**
     *
     * @param username   就是用户登录的时候 输入的账号名
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Login login = loginMapper.selectOne(new LambdaQueryWrapper<Login>().eq(Login::getUsername, username));
        if(login == null){
            return null;
        }
        List<Permission> permissions = loginMapper.selectPermissionByLoginId(login.getId());
        //将权限进行转换为对应的类型
        List<SimpleGrantedAuthority> collect = permissions.stream()
                .map(Permission::getSn).map(SimpleGrantedAuthority::new)
                .collect(Collectors.toList());
        String password = login.getPassword();
        login.setPassword(null);
        redisTemplate.opsForValue().set(Constants.KEY_OF_LOGIN+username,login,24, TimeUnit.HOURS);
        return new User(JSON.toJSONString(login),password,collect);
    }
}
